﻿using iMES.Core.Extensions;
using iMES.Core.Utilities;
using iMES.Entity.DomainModels;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YUN.ProductionManage.IRepositories;
using iMES.Custom.IRepositories;
using YUN.Ware.Repositroies;
using YUN.Ware.IRepositroies;
using System.Data;
using YUN.ProductionManage.Repositories;
using System.Threading.Tasks;
using Castle.Core.Internal;
using YUN.Rawmanagements.IRepositories;
using AutoMapper;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;

namespace YUN.ProductionManage.Services
{
    public partial class Product_ProductPlanningService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IProduct_ProductPlanningRepository _repository;//访问数据库
        private readonly IProduct_ProductOrderRepository _orderrepository;//访问数据库
        private readonly IWare_ProductRepository _productrepository;//访问数据库
        private readonly IWorkingHoursRepository _workingHoursRepository;//访问数据库
        private readonly IMachineToolRepository _machineToolRepository;//访问数据库
        private readonly IBase_RawmanagementRepository _rawRepository;//访问数据库
        private readonly IBase_NumberRuleRepository _numberRuleRepository;//自定义编码规则访问数据库
        [ActivatorUtilitiesConstructor]
        public Product_ProductPlanningService(
            IProduct_ProductPlanningRepository dbRepository,
            IHttpContextAccessor httpContextAccessor,
            IBase_NumberRuleRepository numberRuleRepository,
            IProduct_ProductOrderRepository orderrepository,
            IWare_ProductRepository productrepository,
            IWorkingHoursRepository workingHoursRepository,
            IMachineToolRepository machineToolRepository,
            IBase_RawmanagementRepository rawRepository
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            _numberRuleRepository = numberRuleRepository;
            _orderrepository = orderrepository;
            _productrepository = productrepository;
            _workingHoursRepository = workingHoursRepository;
            _machineToolRepository = machineToolRepository;
            _rawRepository = rawRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        WebResponseContent webResponse = new WebResponseContent();


        /// <summary>
        /// 生产计划排程
        /// </summary>
        /// <param name="productionPlanningId"></param>
        /// <param name="workingHoursList"></param>
        /// <param name="machineToolList"></param>
        /// <param name="planningStartDate"></param>
        /// <param name="planningEndDate"></param>
        /// <returns></returns>
        //    public WebResponseContent BatchAddWorkingHoursAndMachineTools(
        //Guid productionPlanningId,
        //List<WorkingHours> workingHoursList,
        //List<MachineTool> machineToolList,
        //DateTime? planningStartDate,
        //DateTime? planningEndDate)
        //    {
        //        var webResponse = new WebResponseContent();

        //        // 校验参数
        //        if (productionPlanningId == Guid.Empty)
        //            return webResponse.Error("生产计划ID不能为空");
        //        if ((workingHoursList == null || !workingHoursList.Any()) &&
        //            (machineToolList == null || !machineToolList.Any()))
        //            return webResponse.Error("工人工时或机床数据不能为空");

        //        // 获取相关Repository（假设已注入 _workingHoursRepository, _machineToolRepository）
        //        // 并假设有对应的AddRange方法
        //        try
        //        {
        //            // 事务处理
        //            _repository.DbContextBeginTransaction(() =>
        //            {
        //                // 批量添加工人工时
        //                if (workingHoursList != null && workingHoursList.Any())
        //                {
        //                    workingHoursList.ForEach(x => x.ProductionPlanningId = productionPlanningId);
        //                    _workingHoursRepository.AddRange(workingHoursList, false);
        //                }

        //                // 批量添加机床
        //                if (machineToolList != null && machineToolList.Any())
        //                {
        //                    machineToolList.ForEach(x => x.ProductionPlanningId = productionPlanningId);
        //                    _machineToolRepository.AddRange(machineToolList, false);
        //                }

        //                // 更新生产计划的开始/结束日期和状态
        //                var plan = _repository.FindFirst(x => x.ProductionPlanningId == productionPlanningId);
        //                if (plan != null)
        //                {
        //                    var productionOrder =  _orderrepository.FindFirst(x => x.ProductionOrderId == plan.ProductionOrderId);
        //                    if (productionOrder != null)
        //                    {
        //                        // 修改生产订单的状态为 5
        //                        productionOrder.ProductStatus = 5;
        //                        // 更新生产订单的状态
        //                        _orderrepository.Update(productionOrder, x => new { x.ProductStatus }, false);
        //                    }
        //                    plan.PlanningStartDate = planningStartDate;
        //                    plan.PlanningEndDate = planningEndDate;
        //                    // 状态5为“已排程”或自定义
        //                    //plan.ProductStatus = 5;
        //                    _repository.Update(plan, x => new { x.PlanningStartDate, x.PlanningEndDate }, false);
        //                }

        //                _repository.DbContext.SaveChanges();
        //                return webResponse.OK("批量添加成功");
        //            });

        //            return webResponse;
        //        }
        //        catch (Exception ex)
        //        {
        //            return webResponse.Error("批量添加失败：" + ex.Message);
        //        }
        //    }
        /// <summary>
        /// 批量添加或修改工时和机床信息（排程接口调用的服务方法）
        /// </summary>
        public WebResponseContent BatchAddWorkingHoursAndMachineTools(Guid productionPlanningId, List<WorkingHours> workingHoursList, List<MachineTool> machineToolList, DateTime? planningStartDate, DateTime? planningEndDate)
        {
            try
            {
                // 开始事务
                _repository.DbContextBeginTransaction(() =>
                {

                    try
                    {
                        // 1. 更新生产计划的排程日期和状态
                        var plan = _repository.FindFirst(x => x.ProductionPlanningId == productionPlanningId);
                        if (plan != null)
                        {
                            if (planningStartDate.HasValue) plan.PlanningStartDate = planningStartDate.Value;
                            if (planningEndDate.HasValue) plan.PlanningEndDate = planningEndDate.Value;
                            // 状态5为"已排程"或自定义
                            plan.ProductStatus = 5;

                            _repository.Update(plan, x => new { x.PlanningStartDate, x.PlanningEndDate });

                            // 2. 根据生产计划的生产订单ID获取对应的生产订单并修改状态
                            if (!string.IsNullOrEmpty(plan.ProductionOrderId.ToString()))
                            {
                                var productionOrder = _orderrepository.FindFirst(x => x.ProductionOrderId == plan.ProductionOrderId);
                                if (productionOrder != null)
                                {
                                    // 修改生产订单的状态为 5
                                    productionOrder.ProductStatus = 5;
                                    _orderrepository.Update(productionOrder, x => new { x.ProductStatus }, false);
                                }
                            }
                            _orderrepository.DbContext.SaveChanges();
                            _repository.DbContext.SaveChanges();
                        }

                        // 3. 处理工人工时列表
                        foreach (var worker in workingHoursList)
                        {
                            // 查找是否存在相同ID的工时记录
                            var existingWorker = _workingHoursRepository.FindFirst(x => x.WorkingHoursId == worker.WorkingHoursId);
                            List<WorkingHours> updworker = new List<WorkingHours>();
                            if (existingWorker != null)
                            {
                                // 记录存在，执行修改
                                // TODO: 复制 worker 对象中需要更新的属性到 existingWorker
                                existingWorker.WorkerCode = worker.WorkerCode;
                                existingWorker.WorkerName = worker.WorkerName;
                                existingWorker.Department = worker.Department;
                                existingWorker.Team = worker.Team;
                                existingWorker.WorkerState = worker.WorkerState;
                                // 不应该在这里修改 ProductionPlanningId，因为这是该工时记录关联的计划
                                // existingWorker.ProductionPlanningId = worker.ProductionPlanningId; // 谨慎修改关联ID

                                _workingHoursRepository.Update(existingWorker, x => new { x.WorkerCode, x.WorkerName, x.Department, x.Team, x.WorkerState });
                                _workingHoursRepository.DbContext.SaveChanges();
                            }
                            else
                            {
                                // TODO: 获取当前用户创建人
                                // worker.Creator = "System";
                                _workingHoursRepository.Add(worker);
                                _workingHoursRepository.DbContext.SaveChanges();
                            }
                        }


                        // 4. 处理机床列表
                        foreach (var machine in machineToolList)
                        {
                            // 查找是否存在相同ID的机床记录
                            var existingMachine = _machineToolRepository.FindFirst(x => x.MachineId == machine.MachineId);

                            if (existingMachine != null)
                            {
                                // 记录存在，执行修改
                                // TODO: 复制 machine 对象中需要更新的属性到 existingMachine
                                existingMachine.DeviceCode = machine.DeviceCode;
                                existingMachine.DeviceName = machine.DeviceName;
                                existingMachine.DeviceState = machine.DeviceState;
                                existingMachine.DevicePicture = machine.DevicePicture;
                                // existingMachine.ProductionPlanningId = machine.ProductionPlanningId; // 谨慎修改关联ID

                                _machineToolRepository.Update(existingMachine, x => new { x.DeviceCode, x.DeviceName, x.DeviceState, x.DevicePicture });
                            }
                            else
                            {
                                _machineToolRepository.Add(machine);
                                _machineToolRepository.DbContext.SaveChanges();
                                //return webResponse.OK("添加机床成功");
                            }

                        }
                        _repository.DbContext.SaveChanges();
                        _orderrepository.DbContext.SaveChanges();
                        _machineToolRepository.DbContext.SaveChanges();
                        _workingHoursRepository.DbContext.SaveChanges();
                        return webResponse.OK("批量添加成功");
                    }
                    catch (Exception ex)
                    {
                        // 记录异常日志
                        // TODO: Log ex
                        return webResponse.Error("排程异常：" + ex.Message); ;
                    }
                });
                return webResponse;
            }
            catch (Exception ex)
            {
                // 记录异常日志
                // TODO: Log ex
                return webResponse.Error("异常：" + ex.Message); ;
            }
        }



        /// <summary>
        /// 作废生产计划（批量）
        /// </summary>
        /// <param name="planIds">要作废的生产计划ID集合</param>
        /// <returns></returns>
        public WebResponseContent CancelPlans(List<Guid> planIds)
        {
            if (planIds == null || !planIds.Any())
                return webResponse.Error("请选择要作废的生产计划");

            // 查询所有要作废的生产计划
            var plans = _repository.Find(x => planIds.Contains(x.ProductionPlanningId));
            if (plans == null || plans.Count == 0)
                return webResponse.Error("未找到要作废的生产计划");

            // 记录涉及到的生产订单ID
            var orderIds = plans.Select(x => x.ProductionOrderId).Distinct().ToList();

            // 删除生产计划
            try
            {
                _repository.DeleteWithKeys(planIds.Cast<object>().ToArray(), false);

                // 检查每个订单下是否还有剩余的生产计划
                foreach (var orderId in orderIds)
                {
                    bool hasPlan = _repository.Exists(x => x.ProductionOrderId == orderId);
                    if (!hasPlan)
                    {
                        // 找到订单并修改状态为已作废（假设3为已作废状态）
                        var order = _orderrepository.FindFirst(x => x.ProductionOrderId == orderId);
                        if (order != null)
                        {
                            order.ProductStatus = 4; // 3=已作废，按实际枚举调整
                            _orderrepository.Update(order, x => new { x.ProductStatus }, true);
                        }
                    }
                }

                return webResponse.OK("作废成功");
            }
            catch (Exception ex)
            {
                return webResponse.Error("作废失败：" + ex.Message);
            }
        }
        public override PageGridData<ProductionPlanning> GetPageData(PageDataOptions options)
        {
            int pageSize = options.Rows > 0 ? options.Rows : 10;
            int pageIndex = options.Page > 0 ? options.Page : 1;

            // 获取生产计划和生产订单的IQueryable
            var planQuery = _repository.FindAsIQueryable(x => true);
            var orderQuery = _orderrepository.FindAsIQueryable(x => true);
            var productquery = _productrepository.FindAsIQueryable(x => true);
            // 联合查询
            var query = from plan in planQuery
                        join order in orderQuery
                        on plan.ProductionOrderId equals order.ProductionOrderId
                        join product in productquery
                        on plan.ProductId equals product.ProductId
                        select new ProductionPlanning
                        {
                            ProductCode = product.ProductCode,
                            ProductionPlanningId = plan.ProductionPlanningId,
                            ProductionPlanningCode = plan.ProductionPlanningCode,
                            ProductId = plan.ProductId,
                            ProductionOrderId = plan.ProductionOrderId,
                            ReportworkNum = plan.ReportworkNum,
                            CurrentPlanNum = plan.CurrentPlanNum,
                            PlanningStartDate = plan.PlanningStartDate,
                            PlanningEndDate = plan.PlanningEndDate,
                            ActualStartDate = plan.ActualStartDate,
                            ActualEndDate = plan.ActualEndDate,
                            ProductionOrderCode = order.ProductionOrderCode,
                            OrderCode = order.OrderCode,
                            ProductStatus = order.ProductStatus,
                            Remarks = order.Remarks,
                            Priority = order.Priority,
                        };
            int total = query.Count();
            var data = query
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToList();
            return new PageGridData<ProductionPlanning>
            {
                status = 0, // 通常0表示成功
                msg = "OK",
                total = total,
                rows = data,
                summary = null,
                extra = null
            };
        }
        //public override PageGridData<ProductionPlanning> GetPageData(PageDataOptions options)
        //{
        //    int pageSize = options.Rows > 0 ? options.Rows : 10;
        //    int pageIndex = options.Page > 0 ? options.Page : 1;

        //    // 获取生产计划和生产订单的IQueryable
        //    var planQuery = _repository.FindAsIQueryable(x => true);
        //    var orderQuery = _orderrepository.FindAsIQueryable(x => true);
        //    var productquery = _productrepository.FindAsIQueryable(x => true);
        //    // 联合查询
        //    var query = from plan in planQuery
        //                join order in orderQuery
        //                on plan.ProductionOrderId equals order.ProductionOrderId
        //                join product in productquery
        //                on plan.ProductId equals product.ProductId
        //                select new ProductPlanningListDto
        //                {
        //                    ProductType = product.ProductType,
        //                    ProductCode = product.ProductCode,
        //                    ProductionPlanningId = plan.ProductionPlanningId,
        //                    ProductionPlanningCode = plan.ProductionPlanningCode,
        //                    ProductId = plan.ProductId,
        //                    ProductionOrderId = plan.ProductionOrderId,
        //                    ReportworkNum = plan.ReportworkNum,
        //                    CurrentPlanNum = plan.CurrentPlanNum,
        //                    PlanningStartDate = plan.PlanningStartDate,
        //                    PlanningEndDate = plan.PlanningEndDate,
        //                    ActualStartDate = plan.ActualStartDate,
        //                    ActualEndDate = plan.ActualEndDate,
        //                    ProductionOrderCode = order.ProductionOrderCode,
        //                    OrderCode = order.OrderCode,
        //                    ProductStatus = order.ProductStatus,
        //                    Remarks = order.Remarks,
        //                    Priority = order.Priority,
        //                    ProductName = product.ProductName
        //                };
        //    var list = Mapper.Map<IList<ProductionPlanning>>(query);
        //    // 可根据options进行分页、排序、过滤
        //    int total = query.Count();
        //    var data = list
        //        .Skip((pageIndex - 1) * pageSize)
        //        .Take(pageSize)
        //        .ToList();
        //    return new PageGridData<ProductionPlanning>
        //    {
        //        status = 0, // 通常0表示成功
        //        msg = "OK",
        //        total = total,
        //        rows = data,
        //        summary = null,
        //        extra = null
        //    };
        //}
        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            // 1. 查询当天最新的编号
            DateTime dateNow = DateTime.Now.Date;
            // 提取主数据
            var mainData = saveDataModel.MainData;
            if (mainData == null)
            {
                return webResponse.Error("主数据不能为空");
            }
            // 提取明细数据（假设 PlanProductList 在 DetailData 中）
            var detailData = saveDataModel.DetailData;
            if (detailData == null || !detailData.Any())
            {
                return webResponse.Error("明细数据不能为空");
            }

            // 将 DetailData 转换为 PlanProductList
            var planProductList = detailData.Select(d => new
            {
                ProductId = d.ContainsKey("ProductId") ? d["ProductId"].ToString() : null,
                CurrentPlanNum = d.ContainsKey("CurrentPlanNum") ? Convert.ToInt32(d["CurrentPlanNum"]) : 0
            }).ToList();
            // 验证 PlanProductList 数据
            if (!planProductList.Any() || planProductList.Any(p => string.IsNullOrEmpty(p.ProductId) || p.CurrentPlanNum <= 0))
            {
                return webResponse.Error("PlanProductList 数据无效");
            }

            // 构建 data 对象
            var data = new
            {
                ProductionOrderId = mainData.ContainsKey("ProductionOrderId") ? mainData["ProductionOrderId"].ToString() : null,
                Creator = mainData.ContainsKey("Creator") ? mainData["Creator"].ToString() : null,
                PlanProductList = planProductList
            };


            // 获取成品个数和计划产量
            int productCount = planProductList.Count();

            // 获取生产订单ID
            Guid productionOrderId = mainData.ContainsKey("ProductionOrderId") ? Guid.Parse(mainData["ProductionOrderId"].ToString()) : Guid.Empty;
            if (productionOrderId == Guid.Empty)
            {
                return webResponse.Error("生产订单ID无效");
            }
            int startSerial = 1;
            // 查找对应的生产订单
            var productionOrder = _orderrepository.FindFirst(x => x.ProductionOrderId == productionOrderId);
            if (productionOrder == null)
            {
                return webResponse.Error("未找到对应的生产订单");
            }
            string defectItemCode = _repository.FindAsIQueryable(x => x.CreateDate > dateNow && x.ProductionPlanningCode.Length > 8)
        .OrderByDescending(x => x.ProductionPlanningCode)
        .Select(s => s.ProductionPlanningCode)
        .FirstOrDefault();

            Base_NumberRule numberRule = _numberRuleRepository.FindAsIQueryable(x => x.FormCode == "MyProductPlanning")
        .OrderByDescending(x => x.CreateDate)
        .FirstOrDefault();
            if (numberRule != null && !string.IsNullOrEmpty(defectItemCode))
            {
                // 取出当前最大流水号
                string serialStr = defectItemCode.Substring(defectItemCode.Length - numberRule.SerialNumber);
                startSerial = serialStr.GetInt() + 1;
            }
            List<string> productlist = planProductList.Select(x => x.ProductId).ToList();
            // 创建生产计划列表
            var productionPlans = new List<ProductionPlanning>();
            int serial = startSerial;
            for (int i = 0; i < productCount; i++)
            {
                List<int> planQuantity = planProductList.Where(x => x.ProductId == productlist[i]).Select(x => x.CurrentPlanNum).ToList();
                if (productCount <= 0)
                {
                    return webResponse.Error("成品个数无效");
                }
                foreach (var num in planQuantity)
                {
                    if (num <= 0)
                    {
                        return webResponse.Error("成品个数或计划产量无效");
                    }
                    for (int j = 0; j < num; j++)
                    {
                        string planCode;
                        if (numberRule != null)
                        {
                            planCode = numberRule.Prefix + DateTime.Now.ToString(numberRule.SubmitTime.Replace("hh", "HH"))
                                + serial.ToString().PadLeft(numberRule.SerialNumber, '0');
                        }
                        else
                        {
                            planCode = DateTime.Now.ToString("yyyyMMddHHmmssffff");
                        }
                        serial++;
                        var productionPlanning = new ProductionPlanning
                        {
                            ProductionPlanningId = Guid.NewGuid(),
                            ProductionPlanningCode = planCode,
                            ProductId = productlist[i].ToGuid().Value,
                            ProductionOrderId = productionOrderId,
                            CurrentPlanNum = num,
                            ReportworkNum = 0,
                            CreateDate = DateTime.Now,
                            Creator = "系统", // 可替换为当前用户
                        };
                        productionPlans.Add(productionPlanning);
                    }

                }
            }
            // 批量保存生产计划
            try
            {
                _repository.AddRange(productionPlans, saveChanges: true);

                // 更新生产订单状态
                productionOrder.ProductStatus = 2; // 假设状态 2 表示已生成生产计划
                _orderrepository.Update(productionOrder, x => new { x.ProductStatus }, saveChanges: true);

                return webResponse.OK("生产计划添加成功");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return webResponse.Error($"添加生产计划时发生错误: {ex.Message}");
            }
        }



        /// <summary>
        /// 自动生成我的生产计划编号
        /// </summary>
        /// <returns></returns>
        public string GetProductionPlanningCode()
        {
            DateTime dateNow = (DateTime)DateTime.Now.ToString("yyyy-MM-dd").GetDateTime();
            //查询当天最新的订单号
            string defectItemCode = repository.FindAsIQueryable(x => x.CreateDate > dateNow && x.ProductionPlanningCode.Length > 8)
                .OrderByDescending(x => x.ProductionPlanningCode)
                .Select(s => s.ProductionPlanningCode)
                .FirstOrDefault();
            Base_NumberRule numberRule = _numberRuleRepository.FindAsIQueryable(x => x.FormCode == "MyProductPlanning")
                .OrderByDescending(x => x.CreateDate)
                .FirstOrDefault();
            if (numberRule != null)
            {
                string rule = numberRule.Prefix + DateTime.Now.ToString(numberRule.SubmitTime.Replace("hh", "HH"));
                if (string.IsNullOrEmpty(defectItemCode))
                {
                    rule += "1".PadLeft(numberRule.SerialNumber, '0');
                }
                else
                {
                    rule += (defectItemCode.Substring(defectItemCode.Length - numberRule.SerialNumber).GetInt() + 1).ToString("0".PadLeft(numberRule.SerialNumber, '0'));
                }
                return rule;
            }
            else //如果自定义序号配置项不存在，则使用日期生成
            {
                return DateTime.Now.ToString("yyyyMMddHHmmssffff");
            }
        }
    }

}